﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iHouse.Model.Data;
using iHouse.Resource;

namespace iHouse.Web.Infrastructure
{
    public class AlbumBinder : IModelBinder
    {
        #region IModelBinder Members

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;

            bool isNew = true;
            string idStr = request.Form.Get("ID");
            int id;
            if (!string.IsNullOrEmpty(idStr) && int.TryParse(idStr, out id))
            {
                isNew = false;
            }

            string name = request.Form.Get("Name");
            if (string.IsNullOrEmpty(name))
            {
                bindingContext.ModelState.AddModelError("Name", Resources.ExceptionAlbumWithName);
            }

            string date = request.Form.Get("PublishDate");
            DateTime publishDate = DateTime.Now;
            if (!string.IsNullOrEmpty(date) && !DateTime.TryParse(date, out publishDate))
            {
                bindingContext.ModelState.AddModelError("PublishDate", Resources.ExceptionAlbumWithPublishDate);
            }

            Album album = isNew ? new Album() : bindingContext.Model as Album;

            album.Name = name;
            album.Singer = request.Form.Get("Singer");
            album.PublishDate = publishDate;
            album.CategoryID = Convert.ToInt32(request.Form.Get("Category"));
            album.Language = Convert.ToInt32(request.Form.Get("Language"));
            album.Location = request.Form.Get("Location");

            return album;
        }

        #endregion
    }

    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]
    public sealed class AlbumBinderAttribute : CustomModelBinderAttribute
    {
        internal const AttributeTargets ValidTargets = AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Parameter;

        public override IModelBinder GetBinder()
        {
            return new AlbumBinder();
        }
    }
}
